package com.sq.partner.manager.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.sq.partner.manager.common.Constants;
import com.sq.partner.manager.common.Result;
import com.sq.partner.manager.common.exception.AppException;
import com.sq.partner.manager.mybatis.model.GatewayChannelInfo;
import com.sq.partner.manager.mybatis.model.GatewayPolicy;
import com.sq.partner.manager.mybatis.model.GatewayUser;
import com.sq.partner.manager.mybatis.model.TreeDto;
import com.sq.partner.manager.service.IGatewayChannelInfoConfigService;
import com.sq.partner.manager.service.IGatewayCreditPolicyListService;
import com.sq.partner.manager.service.IGatewayCustomerService;
import com.sq.partner.manager.service.IGatewayProductService;
import com.sq.partner.manager.service.INlifeProdConfigService;
import com.sq.partner.manager.util.LogUtil;
import com.sq.partner.manager.util.Page;
import com.sq.partner.manager.util.SqlUtil;
import com.sq.partner.manager.util.StrUtil;
import com.sq.partner.manager.util.excel.ImportExcelBuilderTool;

@Controller
@RequestMapping(value = "/creditPolicyList")
public class CreditPolicyListController {
	private static Logger logger = LogUtil.getLog(CreditPolicyListController.class);
	
	@Resource
	private IGatewayCreditPolicyListService creditPolicyListService;
	
	@Resource
	private IGatewayChannelInfoConfigService channelInfoConfigService;
	
	@Resource
	private IGatewayProductService productService;
	
	@Resource
	private IGatewayCustomerService customerService;
	
	@Resource
	private INlifeProdConfigService nlifeProdConfigService;
	
	@Resource
	ImportExcelBuilderTool importExcelBuilderTool;
	
	/**
	 * 跳转页面
	 */
	@RequestMapping(value = "/index", method = RequestMethod.GET)
	public String index(){
		return "transManager/creditPolicyList";
	}
	
	/**
	 * 查询当前用户的权限机构
	 * @param session
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/queryPrivilegeBranch",method = RequestMethod.POST)
	@ResponseBody
    public Result queryPrivilegeBranch(HttpSession session) throws Exception {
		GatewayUser user=(GatewayUser) session.getAttribute(Constants.SESSION_USER);
		logger.info("当前登录用户的userCode为"+user.getUserCode()+",DepartmentStr:"+user.getDepartmentStr());
		
		if(null != user && StrUtil.isNotEmpty(user.getDepartmentStr())){
			return Result.data(creditPolicyListService.queryPrivilegeBranch(user.getDepartmentStr()));
		}
		
		return Result.fail();
		
    }
	
	/**
	 * 查询合作伙伴
	 * @param fkAppid
	 * @return List<GatewayChannelInfo>
	 * @throws Exception 
	 */
	@RequestMapping(value = "/queryChannelInfoOfLife",method = RequestMethod.POST)
	public @ResponseBody Page<GatewayChannelInfo> queryChannelInfoOfLife(Integer size,Integer pageIndex,
									String parentDeptCode,String channelName,String channelCode) throws Exception{
		if(StrUtil.isEmpty(parentDeptCode)){
			throw new AppException("机构不能为空");
		}
		
		Page<GatewayChannelInfo> page = new Page<GatewayChannelInfo>();
		page.setCurrent(pageIndex);
		page.setSize(size);
		
		GatewayChannelInfo channelInfo = new GatewayChannelInfo();
		channelInfo.setDeptCode(parentDeptCode);
		channelInfo.setChannelCode(channelCode);
		channelInfo.setChannelName(channelName);
		page.setType(channelInfo);
		return creditPolicyListService.queryChannelInfoPageOfLife(page);
	}
	
	/**
	 * 分页条件查询车捷保保单
	 * 
	 */
	@RequestMapping(value = "/queryCreditPolicyPageByCriteria")
	@ResponseBody
   public Page<Map<String,Object>> queryLifePolicyPageByCriteria(HttpSession session, Integer pageIndex,Integer size,
   			GatewayPolicy policy,String privilegeBranch,String tbrName,String polSubDateBegin,String polSubDateEnd,
   			String polBeginDateBegin,String polBeginDateEnd,String subPartnerNo) throws Exception {
		
		Page page = beforeQueryCreditPolicyPageByCriteria(session, pageIndex,size, policy, privilegeBranch,tbrName,polSubDateBegin,polSubDateEnd,polBeginDateBegin, polBeginDateEnd,subPartnerNo);
//		if("error".equals(page.getResult()) || "noChannelInfo".equals(page.getResult())){
//			return page;
//		}
		return creditPolicyListService.queryCreditPolicyPageByCriteria(page);
   }
	
	/**
	 * 信保保单查询和保单信息下载前进行验证
	 */
	public Page beforeQueryCreditPolicyPageByCriteria(HttpSession session, Integer pageIndex,Integer size,
			GatewayPolicy policy,String privilegeBranch,String tbrName,String polSubDateBegin,String polSubDateEnd,
			String polBeginDateBegin,String polBeginDateEnd,String subPartnerNo) throws Exception{
		GatewayUser user = (GatewayUser)session.getAttribute(Constants.SESSION_USER);
		
		Page page = new Page();
		Map<String,Object> map = new HashMap<String, Object>();
		if(pageIndex != -1){
			page.setCurrent(pageIndex);
			map = SqlUtil.buildPageMap(page);
		}
		
		page.setSize(size);
		//机构验证
		if(StrUtil.isEmpty(privilegeBranch)){
			throw new AppException("系统异常：机构不能为空");
		}else{
			if(!(channelInfoConfigService.checkIsHasPrivilege(session, privilegeBranch))){
				throw new AppException("用户权限不足");
			}	
		}
		map.put("privilegeBranch",privilegeBranch);
		//出单机构
//		map.put("dptCode", policy.getDptCde());
		//合作伙伴
		map.put("channelCodeStr", policy.getPartnerNo());
		map.put("tbrName", tbrName);
		//保单提交日期
		if(StrUtil.isNotEmpty(polSubDateBegin)){
			polSubDateBegin = polSubDateBegin + " 00:00:00";
		}
		if(StrUtil.isNotEmpty(polSubDateEnd)){
			polSubDateEnd = polSubDateEnd + " 23:59:59";
		}
		map.put("polSubDateBegin", polSubDateBegin);
		map.put("polSubDateEnd", polSubDateEnd);
		//保单号
		map.put("polno", policy.getPolno());
		//保单生效日期
		if(StrUtil.isNotEmpty(polBeginDateBegin)){
			polBeginDateBegin = polBeginDateBegin + " 00:00:00";
		}
		if(StrUtil.isNotEmpty(polBeginDateEnd)){
			polBeginDateEnd = polBeginDateEnd + " 23:59:59";
		}
		map.put("polBeginDateBegin", polBeginDateBegin);
		map.put("polBeginDateEnd", polBeginDateEnd);
		//保单状态
		map.put("stateId", policy.getStateId());
				
		map.put("isHq", 'N');
		map.put("subPartnerNo", subPartnerNo);
		//合作伙伴代码验证
//		GatewayChannelInfo channelInfo = new GatewayChannelInfo();
//		channelInfo.setDeptCode(privilegeBranch);
//		List<Map> channelInfoList = protocolPolicyListService.queryChannelListOfProtocol(channelInfo,"nocar");
//		if(null == channelInfoList || channelInfoList.size() == 0){
//			page.setResult("noChannelInfo");
//			return page;
//		}
		
//		String channelCodeStr;
//		if(StrUtil.isEmpty(policy.getPartnerNo())){
//			channelCodeStr = "";
////			channelCodeStr = transList2InStr(channelCodeList);
//		}else{
//			List<String> channelCodeList = new ArrayList<String>();
//			for (Map m : channelInfoList) {
//				channelCodeList.add(m.get("CHANNELCODE").toString());
//			}
//			if(!channelCodeList.contains(policy.getPartnerNo())){
//				page.setResult("error");
//				page.setMessage("合作伙伴["+policy.getPartnerNo()+"]没有权限执行此操作");
//				return page;
//			}
//			channelCodeStr="'"+policy.getPartnerNo()+"'";
//		}
		page.setType(map);
		return page;
	}
	
	/**
	 * 导出借意险投保信息
	 */
	@RequestMapping(value = "/downloadCreditPolicyFileByCriteria")
	public void downloadCreditPolicyFileByCriteria(HttpSession session,HttpServletResponse response, Integer pageIndex,Integer size,
			GatewayPolicy policy,String privilegeBranch,String tbrName,String polSubDateBegin,String polSubDateEnd,
			String polBeginDateBegin,String polBeginDateEnd,String subPartnerNo) throws Exception {
	if(null==subPartnerNo){
		subPartnerNo="";
	}
	Page page = beforeQueryCreditPolicyPageByCriteria(session,-1,size, policy, privilegeBranch,tbrName,polSubDateBegin,polSubDateEnd,polBeginDateBegin, polBeginDateEnd,subPartnerNo);

	Map<String,Object> map = (Map<String, Object>) page.getType();
	List<Map<String, Object>> creditPolicyList = creditPolicyListService.queryCreditPolicyListByCriteria(map);
	creditPolicyListService.downloadCreditPolicyFile(creditPolicyList, response);
    }
	/**
	 * 查询信保相关合作伙伴
	 * @param fkAppid
	 * @return List<GatewayChannelInfo>
	 * @throws Exception 
	 */
	@RequestMapping(value = "/querySubChannelTree",method = RequestMethod.POST)
	@ResponseBody
	public List<TreeDto> querySubChannelTree(String parentChannelCode) throws Exception{
		if(StrUtil.isEmpty(parentChannelCode)){
			throw new AppException("合作伙伴代码不能为空");
		}
		
		return channelInfoConfigService.querySubChannelTreeByParentChannelCode(parentChannelCode);
	}
}
	
